package com.esiag.pdsteam.referencement.dao;




import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DataBase{
	private DataSource ds;
	private Connection db;
	public DataBase(DataSource ds){
		super();
		this.ds = ds;
		db = ds.getConnection();
	}
	 
  
    /** 
     * create the database if it doesn't exist 
     * @param path String the directory at which the database will be created it should have file separator in the end 
     * @return created boolean true if the database is created 
     */  
    public boolean createDB(String query,String absPath) {
        boolean created = false;
        File f = new File(absPath);
        if(!f.exists()) return true;
        Statement stat;
		try {
			stat = db.createStatement();
			stat.execute(query);
	        //System.out.println(query);
	        stat.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
        return created;  
    }
    /** 
     * Handles queries that will have results like queries using the "Select" statement 
     * @param query String  the sql query to execute against the database 
     * @return listOfMaps List the result from the query in the form of list of linked hash maps 
     * @throws SQLException 
     * @throws ClassNotFoundException 
     */  
    public ResultSet doQuery(String query) throws SQLException, ClassNotFoundException {   
        Statement stat = db.createStatement();  
        ResultSet rs = stat.executeQuery(query);  
        return rs;  
    }  
  
    /** 
     * Handles queries that won't have results like queries using statements like "create", "drop" or "delete" 
     * @param query String  the sql query to execute against the database 
     * @return rs boolean true if successful 
     * @throws SQLException 
     * @throws ClassNotFoundException 
     */  
    public boolean execQuery(String query) throws SQLException, ClassNotFoundException {  
        Statement stat = db.createStatement();  
        boolean rs = stat.execute(query);
        stat.close();  
        return rs;  
    }
}
